<template>
  <div class="right">
    <div class="name">
      <p>{{ this.data.name }}</p>
    </div>
    <div class="message-container">
      <div
        v-for="(msg, index) in messages"
        :key="msg.id || index"
        :class="{ 'right-message': msg.isMine, 'left-message': !msg.isMine }"
      >
        <p class="message-content">{{ msg.message }}</p>
        <p class="message-time">{{ msg.sendTime }}</p>
      </div>
    </div>
    <div class="message">
      <div class="icon">
        <i class="iconfont">&#xe66f;</i>
        <i class="iconfont"> &#xeac4;</i>
        <i class="iconfont"> &#xe7cc;</i>
        <i class="iconfont">&#xe67b;</i>
      </div>
      <textarea v-model="inputMessage" placeholder="请输入消息内容" class="input-message" @keyup.enter="sendMessage"></textarea>
      <el-button class="button" @click="sendMessage">发送消息</el-button>
    </div>
  </div>
</template>

<script>
import moment from 'moment';
const socket = new WebSocket('ws://websocket.1uu.pw/chat');

export default {
  data() {
    return {
      inputMessage: '',
      // data为点击选中的聊天者，发送消息时的发送者id通过登录时输入的姓名来获取，data是接收消息时的发送者，发送消息时的接受者，
      data: '',
      messages: [],
      currentName: ''
    };
  },
  created() {
    socket.addEventListener('open', this.openHandle);
    socket.addEventListener('error', this.errorHandle);
    socket.addEventListener('close', this.closeHandle);
    socket.addEventListener('message', this.onMessage);
  },
  computed: {
    sharedData() {
      const data = this.$store.getters.getSharedData || '姓名';
      console.log('sharedData:', data);
      return data;
    }
  },
  watch: {
    sharedData(newValue) {
      this.data = newValue;
      this.currentName = newValue.name;
      this.messages = [];
      console.log('sharedData 更新:', newValue);
    }
  },
  methods: {
    sendMessage() {
      if (this.inputMessage) {
        try {
          const currentUser = this.$store.getters.getCurrentUser;
          const messageData = {
            type: 'chat',
            id: Date.now(),
            sendUserId: currentUser.id,
            sendUserName: currentUser.name,
            receivUserId: this.data.id,
            receivUserName: this.data.name,
            message: this.inputMessage,
            sendTime: moment().format('YYYY-MM-DD HH:mm:ss'),
            isMine: true
          };
          socket.send(JSON.stringify(messageData));
          this.messages.push(messageData);
          this.inputMessage = '';
        } catch (error) {
          console.error('消息发送失败:', error);
        }
      }
    },
    // 接收消息
    onMessage(event) {
      try {
        const messageData = JSON.parse(event.data);
        // console.log('接收到的原始消息:', messageData);
        // console.log('处理前 messages 长度:', this.messages.length);
        const currentUser = this.$store.getters.getCurrentUser;
        // 登录的用户 console.log("接收消息时",currentUser);
        const currentChatUserId = this.data.id;
        // console.log("这是选中聊天的对象的id",currentChatUserId);
        if (messageData.type === 'HEARTBEAT' || messageData.sendUserId === currentUser.id) {
          // console.log('过滤掉心跳消息或自己发送的消息');
          return;
        }
        // 只处理与当前选中用户相关的消息
        if (
          // 消息发送者是当前登录用户，接受者是当前登录用户id时
          (messageData.sendUserId === currentChatUserId && messageData.receivUserId === currentUser.id) ||
          (messageData.sendUserId === currentUser.id && messageData.receivUserId === currentChatUserId)
        ) {
          this.messages.push({
            ...messageData,
            isMine: messageData.sendUserId === currentUser.id
          });
          console.log('处理后 messages 长度:', this.messages.length);
        } else {
          console.log('消息与当前选中用户无关，不处理该消息');
        }
      } catch (error) {
        console.error('消息解析失败:', error);
      }
    },
    openHandle() {
      console.log('socket 连接成功');
    },
    errorHandle(error) {
      console.error('socket 连接出错:', error);
    },
    closeHandle() {
      console.log('socket 连接关闭');
    }
  },
  beforeDestroy() {
    // 清理WebSocket连接
    if (socket && socket.readyState !== WebSocket.CLOSED) {
      socket.close();
      console.log('WebSocket 连接已关闭');
    }
    // 移除事件监听器
    socket.removeEventListener('open', this.openHandle);
    socket.removeEventListener('error', this.errorHandle);
    socket.removeEventListener('close', this.closeHandle);
    socket.removeEventListener('message', this.onMessage);
  }
};
</script>

<style lang="scss" scoped>
.right {
  margin-top: -100vh;
  width: 1257px;
  margin-left: 380px;
  height: 100vh; 
  position: relative;
  background-color: #F5F5F5;
  .name {
    width: 100%;
    height: 70px;
    background-color: #F5F5F5;
    border-bottom: 1px solid #bbb9b9;
    font-size: 20px;
    p {
      position: absolute;
      top: 18px;
      margin-left: 10px;
    }
  }
  .message {
    width: 100%;
    height: 300px;
    border-top: #bbb9b9 1px solid;
    position: absolute;
    bottom: 0px;
    background-color: #F5F5F5;
    .icon {
      position: absolute;
      top: 10px;
      left: 0px;
      color: black;
      .iconfont {
        font-size: 21px;
        margin-left: 10px;
      }
    }
    .input-message {
      position: absolute;
      top: 50px;
      left: 0px;
      width: 100%;
      height: 150px;
      background-color: #F5F5F5;
      resize: none;
      outline: none;
      border: #F5F5F5 1px solid;
      font-size: 17px;
    }
    .button {
      position: absolute;
      bottom: 26px;
      right: 20px;
      padding: 8px 18px;
      background-color: #07c160;
      color: white;
      border-radius: 20px;
      &:hover {
        background-color: #06b055;
      }
    }
  }
  .message-container {
    height: calc(100vh - 370px);
    overflow-y: auto;
    padding: 10px;
    scrollbar-width: none;
    background: #F5F5F5;
    // border: 1px solid red;
  }

  .right-message {
    background-color: #07c160;
    color: white;
    border-radius: 15px 15px 0 15px;
    margin: 10px 0;
    padding: 10px;
    max-width: 70%;
    float: right;
    clear: both;
    .message-content {
      margin-bottom: 5px;
    }
    .message-time {
      font-size: 12px;
      text-align: right;
    }
  }

  .left-message {
    background-color: #e5e5e5;
    border-radius: 15px 15px 15px 0;
    margin: 10px 0;
    padding: 10px;
    max-width: 70%;
    float: left;
    clear: both;
    .message-content {
      margin-bottom: 5px;
    }
    .message-time {
      font-size: 12px;
      text-align: left;
    }
  }
}
</style>    